"""
带外管理缓存模块
提供带外管理数据的缓存功能
"""

import logging
import time
from typing import List, Dict, Any, Optional

logger = logging.getLogger(__name__)

class OobCache:
    """带外管理缓存类"""
    
    def __init__(self):
        self.logger = logger
        self._cache = {}
        self._cache_timestamp = {}
        self._cache_ttl = 300  # 缓存有效期5分钟
    
    def get_oob_list(self, force_refresh: bool = False) -> List[Dict[str, Any]]:
        """
        获取带外管理列表（带缓存）
        
        Args:
            force_refresh: 是否强制刷新缓存
            
        Returns:
            带外管理列表
        """
        cache_key = 'oob_list'
        
        # 检查缓存是否存在且未过期
        if not force_refresh and self._is_cache_valid(cache_key):
            self.logger.debug("从缓存获取带外管理列表")
            return self._cache.get(cache_key, [])
        
        return []
    
    def set_oob_list(self, oob_list: List[Dict[str, Any]]) -> None:
        """
        设置带外管理列表缓存
        
        Args:
            oob_list: 带外管理列表
        """
        cache_key = 'oob_list'
        self._cache[cache_key] = oob_list
        self._cache_timestamp[cache_key] = time.time()
        self.logger.debug(f"缓存带外管理列表，共 {len(oob_list)} 条记录")
    
    def get_oob_by_id(self, oob_id: str) -> Optional[Dict[str, Any]]:
        """
        根据ID获取带外管理信息（带缓存）
        
        Args:
            oob_id: 带外管理ID
            
        Returns:
            带外管理信息
        """
        cache_key = f'oob_{oob_id}'
        
        # 检查缓存是否存在且未过期
        if self._is_cache_valid(cache_key):
            self.logger.debug(f"从缓存获取带外管理信息: {oob_id}")
            return self._cache.get(cache_key)
        
        return None
    
    def set_oob_by_id(self, oob_id: str, oob_data: Dict[str, Any]) -> None:
        """
        设置带外管理信息缓存
        
        Args:
            oob_id: 带外管理ID
            oob_data: 带外管理数据
        """
        cache_key = f'oob_{oob_id}'
        self._cache[cache_key] = oob_data
        self._cache_timestamp[cache_key] = time.time()
        self.logger.debug(f"缓存带外管理信息: {oob_id}")
    
    def get_statistics(self, force_refresh: bool = False) -> Dict[str, Any]:
        """
        获取统计信息（带缓存）
        
        Args:
            force_refresh: 是否强制刷新缓存
            
        Returns:
            统计信息
        """
        cache_key = 'oob_statistics'
        
        # 检查缓存是否存在且未过期
        if not force_refresh and self._is_cache_valid(cache_key):
            self.logger.debug("从缓存获取统计信息")
            return self._cache.get(cache_key, {})
        
        return {}
    
    def set_statistics(self, statistics: Dict[str, Any]) -> None:
        """
        设置统计信息缓存
        
        Args:
            statistics: 统计信息
        """
        cache_key = 'oob_statistics'
        self._cache[cache_key] = statistics
        self._cache_timestamp[cache_key] = time.time()
        self.logger.debug("缓存统计信息")
    
    def invalidate_oob_cache(self, oob_id: Optional[str] = None) -> None:
        """
        使缓存失效
        
        Args:
            oob_id: 带外管理ID，如果为None则清空所有缓存
        """
        if oob_id:
            # 使特定带外管理的缓存失效
            cache_key = f'oob_{oob_id}'
            if cache_key in self._cache:
                del self._cache[cache_key]
            if cache_key in self._cache_timestamp:
                del self._cache_timestamp[cache_key]
            self.logger.debug(f"使带外管理缓存失效: {oob_id}")
        else:
            # 清空所有缓存
            self._cache.clear()
            self._cache_timestamp.clear()
            self.logger.debug("清空所有带外管理缓存")
    
    def invalidate_list_cache(self) -> None:
        """
        使列表缓存失效
        """
        cache_key = 'oob_list'
        if cache_key in self._cache:
            del self._cache[cache_key]
        if cache_key in self._cache_timestamp:
            del self._cache_timestamp[cache_key]
        self.logger.debug("使带外管理列表缓存失效")
    
    def invalidate_statistics_cache(self) -> None:
        """
        使统计信息缓存失效
        """
        cache_key = 'oob_statistics'
        if cache_key in self._cache:
            del self._cache[cache_key]
        if cache_key in self._cache_timestamp:
            del self._cache_timestamp[cache_key]
        self.logger.debug("使统计信息缓存失效")
    
    def _is_cache_valid(self, cache_key: str) -> bool:
        """
        检查缓存是否有效
        
        Args:
            cache_key: 缓存键
            
        Returns:
            是否有效
        """
        if cache_key not in self._cache:
            return False
        
        if cache_key not in self._cache_timestamp:
            return False
        
        # 检查是否过期
        cache_time = self._cache_timestamp[cache_key]
        current_time = time.time()
        
        return (current_time - cache_time) < self._cache_ttl
    
    def get_cache_info(self) -> Dict[str, Any]:
        """
        获取缓存信息
        
        Returns:
            缓存信息
        """
        current_time = time.time()
        cache_info = {
            'cache_count': len(self._cache),
            'cache_keys': list(self._cache.keys()),
            'cache_ttl': self._cache_ttl,
            'cache_details': []
        }
        
        for cache_key in self._cache:
            if cache_key in self._cache_timestamp:
                cache_time = self._cache_timestamp[cache_key]
                age = current_time - cache_time
                is_valid = age < self._cache_ttl
                
                cache_info['cache_details'].append({
                    'key': cache_key,
                    'age_seconds': round(age, 2),
                    'is_valid': is_valid,
                    'data_size': len(str(self._cache[cache_key]))
                })
        
        return cache_info
    
    def cleanup_expired_cache(self) -> None:
        """
        清理过期缓存
        """
        current_time = time.time()
        expired_keys = []
        
        for cache_key in self._cache_timestamp:
            cache_time = self._cache_timestamp[cache_key]
            if (current_time - cache_time) >= self._cache_ttl:
                expired_keys.append(cache_key)
        
        for cache_key in expired_keys:
            if cache_key in self._cache:
                del self._cache[cache_key]
            if cache_key in self._cache_timestamp:
                del self._cache_timestamp[cache_key]
        
        if expired_keys:
            self.logger.debug(f"清理过期缓存，共 {len(expired_keys)} 个键")